package com.xichen.config.interceptor;
import com.xichen.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 拦截器
 * @author tang wei
 * @version 1.0
 * @date 2020/7/18 12:22
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 判断用户是否登录，登录返回true，未登录返回false
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws IOException
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //从session中取出用户
        User user=(User) request.getSession().getAttribute("user");
        //空值，代表未登录
        if(user==null){
            //返回到登录页面
            response.sendRedirect(request.getContextPath()+"/pages/index.html");
            return false;
        }
        //有值，放行
        return true;
    }
}
